package com.base.cn.platform.os.controller.user.sms;

import com.base.cn.platform.os.common.constants.ConfigName;
import com.base.cn.platform.os.common.controller.BaseController;
import com.base.cn.platform.os.common.j2cache.CustomCacheChannel;
import com.base.cn.platform.os.common.j2cache.J2CacheRegion;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.email.EmailSendUtils;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.common.utils.sms.SmsSendUtils;
import com.base.cn.platform.os.entity.user.user.CusUser;
import com.base.cn.platform.os.entity.user.user.CuserProfile;
import com.base.cn.platform.os.service.manage.config.SysConfigBiz;
import com.base.cn.platform.os.service.user.user.CusUserBiz;
import com.base.cn.platform.os.service.user.user.CuserProfileBiz;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.TreeMap;

/**
 * 用户发送手机验证码
 *
 * @author s.li
 * @create 2018-06-04-13:48
 */
@RestController
@RequestMapping("/manage/user")
public class UserSendSmsController extends BaseController {

    @Autowired
    private CusUserBiz cusUserBiz;
    @Autowired
    private SysConfigBiz sysConfigBiz;
    @Autowired
    private SmsSendUtils smsSendUtils;
    @Autowired
    private EmailSendUtils emailSendUtils;
    @Autowired
    private CuserProfileBiz cuserProfileBiz;
    @Autowired
    private CustomCacheChannel customCacheChannel;

    /**
     * 发送手机短信验证码
     * @param mobile 手机号
     * @param status  类型，1注册，找回，3绑定，4更换，5完善资料
     * @param sessionId  完善资料时需要传入
     * @return
     */
    @RequestMapping("/sendMobileCode")
    public Map<String,Object> sendMobileCode(@RequestParam("mobile") String mobile,
                                             @RequestParam("status") int status,
                                             @RequestParam(value = "sessionId",required = false) String sessionId){
        Map<String,Object> resultMap;
        boolean sendStatus = true;
        try{
            TreeMap<String,String> configMap = sysConfigBiz.getSysConfigContext(ConfigName.SMS);
            smsSendUtils.setSmsConfig(configMap);
            if(StringUtils.isEmpty(mobile)){
                return ResultUtil.ERROR("请输入手机号码");
            }
            if(!StringUtils.isMobile(mobile)){
                return ResultUtil.ERROR("请填写正确的手机号");
            }
            if(status==1){//注册验证码
                resultMap = this.vMobileExist(mobile);
                if(ObjectUtils.isNotEmpty(resultMap)){
                    return resultMap;
                }
                sendStatus = smsSendUtils.sendRegCode(mobile);
            }
            if(status==2){//找回密码验证码
                if(ObjectUtils.isEmpty(this.vMobileExist(mobile))){
                    return ResultUtil.ERROR("手机号未注册");
                }
                sendStatus = smsSendUtils.sendBackPwdCode(mobile);
            }
            if(status==3){//绑定手机验证码
                resultMap = this.vMobileExist(mobile);
                if(ObjectUtils.isNotEmpty(resultMap)){
                    return resultMap;
                }
                sendStatus = smsSendUtils.sendBindingCode(mobile);
            }
            if(status==4){//更换手机验证码
                if(ObjectUtils.isEmpty(this.vMobileExist(mobile))){
                    return ResultUtil.ERROR("手机号码未绑定");
                }
                sendStatus = smsSendUtils.sendUnBindingCode(mobile);
            }
            if(status==5){//完善用户资料
                resultMap = this.vMobileExist(mobile);
                if(ObjectUtils.isNotEmpty(resultMap)){
                    if(StringUtils.isNotEmpty(sessionId)){
                        CusUser cusUser = (CusUser) customCacheChannel.get(J2CacheRegion.ONE_HOURS_REGION.getKey(),sessionId).getValue();
                        if(cusUser!=null && cusUser.isOther() && DataUtil.idIsNotNull(cusUser.getCpId())){
                            CuserProfile cuserProfile = cuserProfileBiz.findById(cusUser.getCpId());
                            if(ObjectUtils.isEmpty(cuserProfile)){
                                return ResultUtil.ERROR("第三方登录记录不存在");
                            }
                        }else{
                            return resultMap;
                        }
                    }
                }
                sendStatus = smsSendUtils.sendUserInfoCode(mobile);
            }
            if(status==6){//注册268云服务96k
                sendStatus = smsSendUtils.sendVideoCloudServiceCode(mobile);
            }
            if(sendStatus==true){
                resultMap = ResultUtil.SUCCESS("短信发送成功");
            }else{
                resultMap = ResultUtil.ERROR("频繁操作，短信发送失败");
            }
        }catch (Exception e){
            logger.error("sendMobileCode()--error",e);
            resultMap = ResultUtil.ERROR("系统错误，短信发送失败");
        }
        return resultMap;
    }

    /**
     * 发送邮箱验证码
     * @param email 邮箱号
     * @param status 1=注册，2=找回密码，3=绑定邮箱号（用于验证新绑定的邮箱号），4=改绑邮箱号（用于验证原绑定的邮箱号）
     * @return Map<String,Object>
     */
    @RequestMapping("/sendEmailCode")
    public Map<String,Object> sendEmailCode(@RequestParam("email") String email,
                                            @RequestParam("status") int status){
        if(StringUtils.isEmpty(email)){
            return ResultUtil.ERROR("请填写邮箱号");
        }
        if(!StringUtils.isEmail(email)){
            return ResultUtil.ERROR("请填写正确的邮箱号");
        }
        TreeMap<String,String> emailConfigMap = sysConfigBiz.getSysConfigContext(ConfigName.EMAIL);
        emailSendUtils.setEmailConfig(emailConfigMap);
        TreeMap<String,String> infoConfigMap = sysConfigBiz.getSysConfigContext(ConfigName.INFO);
        emailSendUtils.setInfoConfigMap(infoConfigMap);
        Map<String,Object> resultMap = null;
        boolean sendStatus = true;
        if(status ==3){
            //验证邮箱号是否存在
            resultMap = this.vEmailExist(email);
            if(ObjectUtils.isNotEmpty(resultMap)){
                return resultMap;
            }
            sendStatus = emailSendUtils.sendBinding(email);
        }
        if(status ==4){
            resultMap = this.vEmailExist(email);
            if(ObjectUtils.isEmpty(resultMap)){
                return ResultUtil.ERROR("邮箱号未注册绑定");
            }
            sendStatus = emailSendUtils.sendUnBinding(email);
        }
        if(sendStatus==true){
            resultMap = ResultUtil.SUCCESS("邮件发送成功");
        }else{
            resultMap = ResultUtil.ERROR("频繁操作，邮件发送失败");
        }
        return resultMap;
    }

    //==========================================

    /**
     * 验证手机号是否存在
     * @param mobile 手机号
     * @return null验证通过，非验证不通过
     */
    private Map<String,Object> vMobileExist(String mobile){
        CusUser user = cusUserBiz.queryUserByMobile(mobile);
        if(ObjectUtils.isNotEmpty(user)){
            return ResultUtil.ERROR("手机号码已被使用");
        }
        return null;
    }

    /**
     * 验证邮箱号是否存在
     * @param email 邮箱号
     * @return  null验证通过，非验证不通过
     */
    private Map<String,Object> vEmailExist(String email){
        CusUser user= cusUserBiz.queryUserByEmail(email);
        if(ObjectUtils.isNotEmpty(user)){
            return ResultUtil.ERROR("邮箱号已被使用");
        }
        return null;
    }
}
